package com.lening.community.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lening.common.base.BaseController;
import com.lening.community.dto.ShopsDto;
import com.lening.community.pojo.House;
import com.lening.community.pojo.Shops;
import com.lening.community.service.Record1Service;
import com.lening.community.service.ShopsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.reactive.function.client.WebClient;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import static jdk.nashorn.internal.runtime.regexp.joni.Config.log;

/**
 * @ToDo:
 * @Author：潘万法
 * @date: 2024/6/3 17:07
 */
@RestController
@RequestMapping("shop")
public class ShopsController extends BaseController<Shops, ShopsDto, ShopsService> {
    @Autowired(required = false)
    private ShopsService shopsService;
    @Autowired(required = false)
    private WebClient webClient;
    @Autowired(required = false)
    private Record1Service record1Service;

//    @GetMapping("pages")
//    public Page<Shops> getShops(ShopsDto shopsDto) {
//        Page<Shops> page = shopsService.page(shopsDto);
//        return page;
//    }

    /**
     * 查询商铺数量
     */
    @GetMapping("getCount")
    public int getCount() {
        return shopsService.getCount();
    }

    //导出
    @PostMapping("ExportExcel")
    public void ExportExcel() {
        // 设置文件导出的路径
        String realPath = "D://wsfile/";
        File folder = new File(realPath);
        if (!folder.isDirectory()){
            folder.mkdirs();
        }
        String fileName = realPath  + "Store" + System.currentTimeMillis() + ".xlsx";
        EasyExcel.write(fileName, Shops.class).sheet("用户表").doWrite(shopsService.find());
    }

    //导入
    @Transactional(rollbackFor = Exception.class) // 指定任何异常都要回滚事务
    @PostMapping("ImportExcel")
    public void ImportExcel(MultipartFile multipartFile) throws IOException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        if (multipartFile.isEmpty()) {
            return;
        }
        // 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
        // 这里每次会读取3000条数据 然后返回过来 直接调用使用数据就行
        EasyExcel.read(multipartFile.getInputStream(), Shops.class, new PageReadListener<Shops>(dataList -> {
            int filedCount=0;
            //获取文件中的总数
            System.out.println(dataList.size());
            try{
                if(1000<dataList.size()){
                    for(int i = 0; i < 1000000 /1000;i++){
                        Future<Boolean> result = executorService.submit(() -> {
                            return shopsService.saveBatch(dataList);
                        });
                    }
                }else {
                    for (Shops shops : dataList) {

                            try {
                                //调用insert方法将导入的数据用mybatisPlus一个个添加进数据库
                                if (shops.getShopNum() ==null) {
                                    throw new IllegalArgumentException("Invalid value for someField: ");
                                }
                                //将导入的数据用mybatisPlus一个个添加进数据库
                                shopsService.insert(shops);
                            }catch(Exception e){
                                filedCount++;
                                log.print("导入失败，失败数为"+filedCount);
                            }
                    }

                    record1Service.adda((long) dataList.size(),(long) dataList.size()-filedCount, (long) filedCount);
                }
            }catch (Exception e){
                log.print("导入失败");
            }
        })).sheet().doRead();
    }
}
